package com.dolphin.apipassenger.controller;

import com.dolphin.apipassenger.request.OrderRequest;
import com.dolphin.apipassenger.service.ServiceOrderService;
import com.dolphin.common.constant.CommonStatusEnum;
import com.dolphin.common.constant.IdentityConstant;
import com.dolphin.common.dto.OrderInfo;
import com.dolphin.common.dto.ResponseResult;
import com.dolphin.common.dto.TokenResult;
import com.dolphin.common.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;

@RestController
@RequestMapping("/order")
@Slf4j
@Validated
public class OrderController {
    @Autowired
    private ServiceOrderService serviceOrderService;

    /**
     * 创建订单/下单
     * @param orderRequest
     * @return
     */
    @PostMapping("/add")
    public ResponseResult add(@Validated @RequestBody OrderRequest orderRequest){
        log.info("下单请求：{}",orderRequest);
        return serviceOrderService.add(orderRequest);
    }
    @PostMapping("/book")
    public ResponseResult book(@Validated @RequestBody OrderRequest orderRequest){
        log.info("预约下单请求：{}",orderRequest);
        return serviceOrderService.book(orderRequest);
    }

    @PostMapping("/cancel")
    public ResponseResult cancel(@RequestParam @NotNull @Positive Long orderId) {
        return serviceOrderService.cancel(orderId);

    }
    @GetMapping("/detail")
    public ResponseResult<OrderInfo> detail(@NotNull(message = "订单id不能为空") @Positive(message = "订单id格式不正确") Long orderId){
        return serviceOrderService.detail(orderId);
    }
    @GetMapping("/current")
    public ResponseResult<OrderInfo> currentOrder(HttpServletRequest httpServletRequest){
        String authorization = httpServletRequest.getHeader("Authorization");
        TokenResult tokenResult = JwtUtils.parseToken(authorization);
        String identity = tokenResult.getIdentity();
        if (!identity.equals(IdentityConstant.PASSENGER_IDENTITY)){
            return ResponseResult.fail(CommonStatusEnum.TOKEN_ERROR.getCode(),CommonStatusEnum.TOKEN_ERROR.getValue());
        }
        String phone = tokenResult.getPhone();

        return serviceOrderService.currentOrder(phone,IdentityConstant.PASSENGER_IDENTITY);
    }
}
